package service

import (
	"context"
	"gorm.io/gorm"
	"video-srv/basic/global"
	__ "video-srv/basic/prorto"
	"video-srv/internal/model"
)

type Service struct {
	__.UnimplementedVideoServer
}

func (s *Service) VideoList(_ context.Context, req *__.VideoListReq) (resp *__.VideoListResp, err error) {

	var videos []model.VideoSearchParams

	tx := global.DB.Debug().Model(&model.Video{}).
		Select("videos.id, videos.title,videos.play_count, channels.NAME AS channel_name, video_areas.NAME AS area_name,video_pay_types.types_name AS pay_type_name ").
		Joins("left JOIN channels ON videos.channel_id = channels.id").
		Joins("left JOIN video_areas ON videos.area_id = video_areas.id").
		Joins("left JOIN video_pay_types ON videos.pay_id = video_pay_types.id ")

	if req.TitleKeyword != "" {
		tx = tx.Where("title LIKE ?", "%"+req.TitleKeyword+"%")
	}

	if req.AreaName != "" {
		tx = tx.Where("area_name = ?", req.AreaName)
	}

	if req.ChannelName != "" {
		tx = tx.Where("channel_name = ?", req.ChannelName)
	}

	if req.PayTypeName != "" {
		tx = tx.Where("pay_type_name = ?", req.PayTypeName)
	}

	if req.MinPlayCount != 0 {
		tx = tx.Where("play_count > ?", req.MinPlayCount)
	}

	if req.SortBy != "" {
		tx = tx.Order("play_count desc")
	}

	tx.Scopes(Paginate(int(req.Page), int(req.Size))).Find(&videos)

	var videoList []*__.VideoList

	for _, video := range videos {
		list := &__.VideoList{
			Id:          int64(video.ID),
			Title:       video.Title,
			PlayCount:   video.PlayCount,
			ChannelName: video.ChannelName,
			AreaName:    video.AreaName,
			PayTypeName: video.PayTypeName,
		}
		videoList = append(videoList, list)
	}

	resp = &__.VideoListResp{List: videoList}

	return resp, nil

}
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
